/**
 * @description 定时按钮
 */
import style from './styles/App.less';

import React from 'react';
import classnames from 'classnames';

let timmer = null;//定时器

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      autoTrigger: props.autoTrigger, // 自动触发一次点击
      second: 0, // 倒计时时间
      lock: false // 倒计时锁
    };
  }

  //检测是否被锁住
  run() {
    if (this.props.disabled) {
      this.props.disabledClick();
    }
    else if (!this.state.lock) {
      this.props.validClick(()=>{
        this.validClick()
      });
    }
  }

  // 有效点击
  validClick(){
    this.checkLockAndRun(this.props.timeSpan);
  }

  //倒计时
  checkLockAndRun(second) {
    //如果倒计时还没结束
    if (second) {
      //设置倒计时时间和锁
      this.setState({
        second: second,
        lock: true
      });

      timmer = setTimeout(() => {
        this.checkLockAndRun(second - 1);
      }, 1000);
    } else {
      //如果倒计时结束，解锁
      this.setState({
        second: 0,
        lock: false
      });
    }
  }

  componentDidMount() {
    if (this.state.autoTrigger) {
      this.run();
    }
  }

  componentWillUnmount() {
    clearTimeout(timmer);
  }

  render() {
    return (
      <button className={classnames('x-timmer-btn', {
        [this.props.className]: !!this.props.className
      })} onClick={this.run.bind(this)}>
        {
          (this.state.lock ? this.props.lockText : this.props.normalText)
          + (this.state.second ? ('(' + this.state.second + ')') : '')
        }
      </button>
    );
  }
}

App.defaultProps = {
  autoTrigger: false, // 自动触发一次点击
  disabled: false, // 禁用按钮
  normalText: '点击发送',// 常规状态的文案
  lockText: '重新发送',// 锁定状态的文案
  timeSpan: 60, //倒计时间隔
  validClick: () => { }, // 有效点击
  disabledClick: () => { } // 禁用状态下的点击
};

export default App;
